package com.deyou.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deyou.AppManager;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.SimpleResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.CountDownTimerUtils;
import com.deyou.util.Urls;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscription;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ForgetPwdActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.findpwd_header_layout)
    RelativeLayout findPwdHeaderLayout;
    @BindView(R.id.find_pwd_type)
    TextView findPwdType;
    @BindView(R.id.tv_phone_title)
    TextView tvPhoneTitle;
    @BindView(R.id.tv_phone_area_code)
    TextView tvPhoneAreaCode;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.phone_layout)
    RelativeLayout phoneLayout;
    @BindView(R.id.tv_mail_title)
    TextView tvMailTitle;
    @BindView(R.id.et_mail)
    EditText etMail;
    @BindView(R.id.mail_layout)
    RelativeLayout mailLayout;
    @BindView(R.id.tv_code_title)
    TextView tvCodeTitle;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_authcode)
    TextView btnAuthcode;
    @BindView(R.id.authcode_layout)
    RelativeLayout authcodeLayout;
    @BindView(R.id.tv_pwd_title)
    TextView tvPwdTitle;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.ic_nosee_pwd)
    ImageView icNoseePwd;
    @BindView(R.id.password_layout)
    RelativeLayout passwordLayout;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.btn_use_other_type)
    TextView btnUseOtherType;
    private boolean flag;
    private boolean usedPhone; // false-手机找回 true-邮箱找回

    private CountDownTimerUtils timerUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);
        ButterKnife.bind(this);
        flag = true;
        usedPhone = false;
    }

    @OnClick({R.id.iv_back, R.id.tv_phone_area_code, R.id.btn_authcode, R.id.ic_nosee_pwd, R.id.btn_confirm, R.id.btn_use_other_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_phone_area_code:
                break;
            case R.id.btn_authcode:
                if (usedPhone){
                    if (TextUtils.isEmpty(etPhone.getText().toString().trim())){
                        showToast("手机号不能为空");
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(etMail.getText().toString().trim())){
                        showToast("邮箱不能为空");
                        return;
                    }
                }
                sendAuthCode(usedPhone);
                break;
            case R.id.ic_nosee_pwd:
                if (TextUtils.isEmpty(etPassword.getText().toString().trim()))
                    return;
                if(flag == true){
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flag = false;
                    icNoseePwd.setImageResource(R.drawable.ic_see_pwd);
                }else{
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flag = true;
                    icNoseePwd.setImageResource(R.drawable.ic_nosee_pwd);
                }
                etPassword.setSelection(etPassword.getText().length());
                break;
            case R.id.btn_confirm:
                if (usedPhone){
                    if (TextUtils.isEmpty(etPhone.getText().toString().trim())){
                        showToast("手机号不能为空");
                        return;
                    }
                } else {
                    if (TextUtils.isEmpty(etMail.getText().toString().trim())){
                        showToast("邮箱不能为空");
                        return;
                    }
                }
                if (TextUtils.isEmpty(etCode.getText().toString().trim())){
                    showToast("验证码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etPassword.getText().toString().trim())){
                    showToast("新设密码不能为空");
                    return;
                }
                updateUserPwd();
                break;
            case R.id.btn_use_other_type:
                if (usedPhone){
                    phoneLayout.setVisibility(View.GONE);
                    mailLayout.setVisibility(View.VISIBLE);
                    findPwdType.setText("(通过邮箱验证码的方式重设密码)");
                    btnUseOtherType.setText("使用手机账号");
                    usedPhone = false;
                    findPwdHeaderLayout.setBackgroundResource(R.drawable.bg_mail_findpwd);
                } else {
                    phoneLayout.setVisibility(View.VISIBLE);
                    mailLayout.setVisibility(View.GONE);
                    findPwdType.setText("(通过手机验证码的方式重设密码)");
                    btnUseOtherType.setText("使用邮箱账号");
                    usedPhone = true;
                    findPwdHeaderLayout.setBackgroundResource(R.drawable.bg_phone_findpwd);
                }
                break;
        }
    }

    private void sendAuthCode(boolean isPhone) {
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            if (isPhone)
                object.put("phone", etPhone.getText().toString().trim());
            else
                object.put("mailbox", etMail.getText().toString().trim());
            String paramJson = object.toString();
            ServerApi.getString(isPhone ? Urls.sencodes : Urls.sendemail, "", AESUtil.encrypt(paramJson))
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("获取验证码...");
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp){
                                b.putString("errMsg", resp.msg);
                                if (resp.code == 1){
                                    b.putInt("code", 1);
                                } else {
                                    b.putInt("code", 2);
                                }
                                msg.setData(b);
                                handler.sendMessage(msg);
                            } else {
                                b.putInt("code", 3);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            b.putInt("code", 3);
                            msg.setData(b);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updateUserPwd(){
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            object.put("userLogin", usedPhone ? etPhone.getText().toString().trim() : etMail.getText().toString().trim());
            object.put("userPassword", etPassword.getText().toString().trim());
            String paramJson = object.toString();
            ServerApi.getString(Urls.updateuserpassword, "", AESUtil.encrypt(paramJson))
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("密码重置中...");
                        }
                    }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp){
                                b.putString("errMsg", resp.msg);
                                if (resp.code == 1){
                                    b.putInt("code", 4);
                                } else {
                                    b.putInt("code", 2);
                                }
                                msg.setData(b);
                                handler.sendMessage(msg);
                            } else {
                                b.putInt("code", 5);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            b.putInt("code", 5);
                            msg.setData(b);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.getData().getInt("code");
            switch (code){
                case 1:
                    timerUtil = new CountDownTimerUtils(btnAuthcode, 60000, 1000, 1);
                    timerUtil.start();
                    break;
                case 2:
                    String errMsg = msg.getData().getString("errMsg");
                    showToast(errMsg);
                    break;
                case 3:
                    showToast("获取验证码失败");
                    break;
                case 4:
                    showToast("重设密码成功,请重新登录");
                    AndroidUtils.startNextActivity(ForgetPwdActivity.this, LoginActivity.class, null, false);
                    AppManager.getAppManager().finishAllActivity(LoginActivity.class);
                    break;
                case 5:
                    showToast("重设密码失败");
                    break;
            }
        }
    };
}
